package auth_server

import (
	"context"
	"strings"
	"time"

	"google.golang.org/grpc"
	common "jihe.common"
	"jihe.common/protos/auth_server/proto"
)

var once = false
var conns []proto.AuthClient

func GetClient() []proto.AuthClient {
	if !once {
		for i := 0; i < len(common.Configer.Grpc.AuthServers); i++ {
			grpcConn, err := grpc.Dial(common.Configer.Grpc.AuthServers[i], grpc.WithInsecure())
			if err != nil {
				return conns
			}
			conns = append(conns, proto.NewAuthClient(grpcConn))
		}
		once = true
	}
	return conns
}

func CreateToken(c context.Context, in *proto.CreateTokenReq) (out *proto.CreateTokenRes, err error) {
	clients := GetClient()
	num := time.Now().UnixNano()
	for i := 0; i < len(clients); i++ {
		index := (num + int64(i)) % int64(len(clients))
		out, err = clients[index].CreateToken(c, in)
		if err != nil && strings.Contains(err.Error(), "connection refused") {
			//fmt.Println(err.Error())
		} else {
			return
		}
	}
	return
}

func VerifyToken(c context.Context, in *proto.VerifyTokenReq) (out *proto.VerifyTokenRes, err error) {
	clients := GetClient()
	num := time.Now().UnixNano()
	for i := 0; i < len(clients); i++ {
		index := (num + int64(i)) % int64(len(clients))
		out, err = clients[index].VerifyToken(c, in)
		if err != nil && strings.Contains(err.Error(), "connection refused") {
			//fmt.Println(err.Error())
		} else {
			return
		}
	}
	return
}
